import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/music_provider.dart';
import '../utils/lyric_parser.dart';

class PlayerScreen extends ConsumerWidget {
  const PlayerScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final playerState = ref.watch(playerProvider);
    final favoritesNotifier = ref.read(favoritesProvider.notifier);
    final favorites = ref.watch(favoritesProvider);

    if (playerState.currentMusic == null) {
      return Scaffold(
        backgroundColor: const Color(0xFFF8FFFE),
        appBar: AppBar(
          title: const Text(
            '播放器',
            style: TextStyle(
              fontWeight: FontWeight.w600,
              color: Color(0xFF2D3748),
            ),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          iconTheme: const IconThemeData(color: Color(0xFF4A5568)),
        ),
        body: Center(
          child: Container(
            margin: const EdgeInsets.all(32),
            padding: const EdgeInsets.all(40),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(24),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 20,
                  offset: const Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: const EdgeInsets.all(24),
                  decoration: BoxDecoration(
                    color: const Color(0xFFEDF2F7),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Icon(
                    Icons.music_off,
                    size: 80,
                    color: Color(0xFF718096),
                  ),
                ),
                const SizedBox(height: 24),
                const Text(
                  '暂无播放音乐',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF4A5568),
                  ),
                ),
                const SizedBox(height: 8),
                const Text(
                  '从搜索页面选择音乐开始播放',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF718096),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    final music = playerState.currentMusic!;
    final isFavorite = favorites.contains(music);

    return Scaffold(
      backgroundColor: const Color(0xFFF8FFFE),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.white,
              const Color(0xFFF8FFFE),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.05),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: const Icon(
                          Icons.arrow_back,
                          color: Color(0xFF4A5568),
                        ),
                        onPressed: () => Navigator.of(context).pop(),
                      ),
                    ),
                    const Expanded(
                      child: Text(
                        '正在播放',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Color(0xFF2D3748),
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: isFavorite 
                            ? const Color(0xFFFED7D7) 
                            : Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.05),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: Icon(
                          isFavorite ? Icons.favorite : Icons.favorite_border,
                          color: isFavorite 
                              ? const Color(0xFFE53E3E) 
                              : const Color(0xFF4A5568),
                        ),
                        onPressed: () {
                           if (isFavorite) {
                             favoritesNotifier.removeFavorite(music);
                           } else {
                             favoritesNotifier.addFavorite(music);
                           }
                         },
                      ),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 20),

              // 封面图片
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 40),
                width: double.infinity,
                height: 220,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(24),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.15),
                      blurRadius: 30,
                      offset: const Offset(0, 15),
                    ),
                  ],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(24),
                  child: music.pic != null && music.pic!.isNotEmpty
                      ? Image.network(
                          music.pic!,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return _buildDefaultCover();
                          },
                        )
                      : _buildDefaultCover(),
                ),
              ),

              const SizedBox(height: 30),

              // 歌曲信息
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 32),
                child: Column(
                  children: [
                    Text(
                      music.title,
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.w700,
                        color: Color(0xFF2D3748),
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    Text(
                       music.author,
                       style: const TextStyle(
                         fontSize: 16,
                         color: Color(0xFF718096),
                       ),
                       textAlign: TextAlign.center,
                       maxLines: 1,
                       overflow: TextOverflow.ellipsis,
                     ),
                     const SizedBox(height: 8),
                     Container(
                       padding: const EdgeInsets.symmetric(
                         horizontal: 12,
                         vertical: 4,
                       ),
                       decoration: BoxDecoration(
                         color: _getSourceColor(music.type).withOpacity(0.1),
                         borderRadius: BorderRadius.circular(12),
                       ),
                       child: Text(
                         _getSourceName(music.type),
                         style: TextStyle(
                           color: _getSourceColor(music.type),
                           fontSize: 12,
                           fontWeight: FontWeight.w600,
                         ),
                       ),
                     ),
                  ],
                ),
              ),

              const SizedBox(height: 40),

              // 歌词显示
              _buildLyricsSection(music, playerState.position),

              const SizedBox(height: 30),

              // 进度条
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 32),
                child: Column(
                  children: [
                    SliderTheme(
                      data: SliderTheme.of(context).copyWith(
                        activeTrackColor: const Color(0xFF667EEA),
                        inactiveTrackColor: const Color(0xFFE2E8F0),
                        thumbColor: const Color(0xFF667EEA),
                        overlayColor: const Color(0xFF667EEA).withOpacity(0.2),
                        thumbShape: const RoundSliderThumbShape(
                          enabledThumbRadius: 8,
                        ),
                        trackHeight: 4,
                      ),
                      child: Slider(
                        value: playerState.position.inSeconds.toDouble(),
                        max: playerState.duration.inSeconds.toDouble().clamp(1.0, double.infinity),
                        onChanged: (value) {
                          final position = Duration(seconds: value.toInt());
                          ref.read(playerProvider.notifier).seek(position);
                        },
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          _formatDuration(playerState.position),
                          style: const TextStyle(
                            color: Color(0xFF718096),
                            fontSize: 12,
                          ),
                        ),
                        Text(
                          _formatDuration(playerState.duration),
                          style: const TextStyle(
                            color: Color(0xFF718096),
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 30),

              // 控制按钮
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 40),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.05),
                            blurRadius: 8,
                            offset: const Offset(0, 4),
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: const Icon(
                          Icons.skip_previous,
                          color: Color(0xFF4A5568),
                        ),
                        iconSize: 32,
                        onPressed: () {
                          // TODO: 实现上一首
                        },
                      ),
                    ),
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFF667EEA), Color(0xFF764BA2)],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(40),
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFF667EEA).withOpacity(0.4),
                            blurRadius: 20,
                            offset: const Offset(0, 8),
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: Icon(
                          playerState.isPlaying ? Icons.pause : Icons.play_arrow,
                          color: Colors.white,
                        ),
                        iconSize: 40,
                        onPressed: () {
                          ref.read(playerProvider.notifier).togglePlayPause();
                        },
                      ),
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.05),
                            blurRadius: 8,
                            offset: const Offset(0, 4),
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: const Icon(
                          Icons.skip_next,
                          color: Color(0xFF4A5568),
                        ),
                        iconSize: 32,
                        onPressed: () {
                          // TODO: 实现下一首
                        },
                      ),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDefaultCover() {
    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFFEDF2F7), Color(0xFFE2E8F0)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(24),
      ),
      child: const Center(
        child: Icon(
          Icons.music_note,
          color: Color(0xFF718096),
          size: 80,
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  Color _getSourceColor(String type) {
    switch (type.toLowerCase()) {
      case 'netease':
        return const Color(0xFFE53E3E);
      case 'qq':
        return const Color(0xFF38B2AC);
      case 'kugou':
        return const Color(0xFF3182CE);
      case 'kuwo':
        return const Color(0xFFD69E2E);
      default:
        return const Color(0xFF718096);
    }
  }

  String _getSourceName(String type) {
    switch (type.toLowerCase()) {
      case 'netease':
        return '网易云音乐';
      case 'qq':
        return 'QQ音乐';
      case 'kugou':
        return '酷狗音乐';
      case 'kuwo':
        return '酷我音乐';
      default:
        return type.toUpperCase();
    }
  }

  Widget _buildLyricsSection(music, Duration currentPosition) {
    final lyrics = LyricParser.parse(music.lrc);
    if (lyrics.isEmpty) {
      return Container(
        height: 120,
        padding: const EdgeInsets.symmetric(horizontal: 32),
        child: const Center(
          child: Text(
            '暂无歌词',
            style: TextStyle(
              color: Color(0xFF718096),
              fontSize: 16,
            ),
          ),
        ),
      );
    }

    final currentIndex = LyricParser.getCurrentLyricIndex(lyrics, currentPosition);
    
    return Container(
      height: 120,
      padding: const EdgeInsets.symmetric(horizontal: 32),
      child: _LyricScrollView(
        lyrics: lyrics,
        currentIndex: currentIndex,
      ),
    );
  }
}

class _LyricScrollView extends StatefulWidget {
  final List<LyricLine> lyrics;
  final int currentIndex;

  const _LyricScrollView({
    required this.lyrics,
    required this.currentIndex,
  });

  @override
  State<_LyricScrollView> createState() => _LyricScrollViewState();
}

class _LyricScrollViewState extends State<_LyricScrollView> {
  late ScrollController _scrollController;
  int _lastCurrentIndex = -1;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(_LyricScrollView oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 当当前歌词索引发生变化时，自动滚动到对应位置
    if (widget.currentIndex != _lastCurrentIndex && widget.currentIndex >= 0) {
      _lastCurrentIndex = widget.currentIndex;
      _scrollToCurrentLyric();
    }
  }

  void _scrollToCurrentLyric() {
    if (!_scrollController.hasClients) return;
    
    // 计算目标滚动位置，让当前歌词显示在中央
    const itemHeight = 32.0; // 每行歌词的高度（包括padding）
    final containerHeight = 120.0; // 容器高度
    final targetOffset = (widget.currentIndex * itemHeight) - (containerHeight / 2) + (itemHeight / 2);
    
    // 确保滚动位置在有效范围内
    final maxScrollExtent = _scrollController.position.maxScrollExtent;
    final clampedOffset = targetOffset.clamp(0.0, maxScrollExtent);
    
    _scrollController.animateTo(
      clampedOffset,
      duration: const Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      controller: _scrollController,
      itemCount: widget.lyrics.length,
      itemBuilder: (context, index) {
        final lyric = widget.lyrics[index];
        final isCurrentLine = index == widget.currentIndex;
        final isNextLine = index == widget.currentIndex + 1;
        final isPrevLine = index == widget.currentIndex - 1;
        
        return AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: Text(
            lyric.text,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: isCurrentLine ? 18 : 14,
              fontWeight: isCurrentLine ? FontWeight.w600 : FontWeight.w400,
              color: isCurrentLine 
                  ? const Color(0xFF667EEA)
                  : (isNextLine || isPrevLine)
                      ? const Color(0xFF4A5568)
                      : const Color(0xFF718096),
            ),
          ),
        );
      },
    );
  }
}